package com.alibaba.sentinelapi;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author YL
 * @date 14:05 2021/10/9
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/initFlowRules")
    public String init() {
        initFlowRules();
        return "init";
    }

    private static void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("/test/hello");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(1);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

    @GetMapping("hello")
    public String hello(@RequestParam(value = "name", required = false) String name) {
        return "hello";
    }

    @GetMapping("sayHello")
    public String sayHello(@RequestParam(value = "name", required = false) String name) {
        Entry entry = null;
        try {
            entry = SphU.entry("sayHello");
            if (StringUtil.isBlank(name)) {
                throw new IllegalArgumentException("不能为空");
            }
            return "xx:" + name;
        } catch (BlockException e) {
            log.warn("限流，或者降级了", e);
            return "限流，或者降级了";
        } catch (IllegalArgumentException e2) {
            Tracer.trace(e2);
            return "参数非法";
        } catch (Exception ex) {
            Tracer.traceEntry(ex, entry);
            return ex.getMessage();
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
    }

    @GetMapping("sayHelloRules")
    public String sayHelloRules() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("sayHello");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(1);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
        return "sayHelloRules";
    }
}
